package com.cameron.serviceedu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cameron.serviceedu.entity.EduChapter;
import com.cameron.serviceedu.entity.EduVideo;
import com.cameron.serviceedu.entity.dto.ChapterDto;
import com.cameron.serviceedu.mapper.EduChapterMapper;
import com.cameron.serviceedu.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cameron.serviceedu.service.EduVideoService;
import com.cameron.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author cameron
 * @since 2022-06-17
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Resource
    private EduVideoService videoService;

    @Override
    @Transactional
    public List<ChapterDto> getAll(String curseId) {
        //1.通过课程id获取该课程的所有章节
        LambdaQueryWrapper<EduChapter> lqw = new LambdaQueryWrapper<>();
        lqw.eq(EduChapter::getCourseId, curseId);
        List<EduChapter> chapterList = this.list(lqw);

        //2.通过章节id来获取小节列表并映射为dto对象
        return chapterList.stream().map((chapter) -> {
            ChapterDto dto = new ChapterDto();
            BeanUtils.copyProperties(chapter, dto);
            LambdaQueryWrapper<EduVideo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(EduVideo::getChapterId, chapter.getId());
            List<EduVideo> list = videoService.list(wrapper);
            dto.setChildren(list);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public Result delChapter(String chapterId) {
        //查询该章节中是否有小节
        LambdaQueryWrapper<EduVideo> lqw = new LambdaQueryWrapper<>();

        lqw.eq(EduVideo::getChapterId, chapterId);
        int i = videoService.count(lqw);
        //如果存在小节 则提示错误
        if (i > 0) {
            return Result.error().message("该章节中有小节，请先删除小节后再删除章节！");
        }
        return this.removeById(chapterId) ? Result.ok() : Result.error();
    }
}
